home *** CD-ROM | disk | FTP | other *** search
/ Personal Computer World 2009 February / PCWFEB09.iso / Software / Linux / Kubuntu 8.10 / kubuntu-8.10-desktop-i386.iso / casper / filesystem.squashfs / usr / lib / python2.5 / idlelib / configHandler.py < prev    next >
Text File  |  2008-10-05  |  29KB  |  714 lines

  1. """Provides access to stored IDLE configuration information.
  2.  
  3. Refer to the comments at the beginning of config-main.def for a description of
  4. the available configuration files and the design implemented to update user
  5. configuration information.  In particular, user configuration choices which
  6. duplicate the defaults will be removed from the user's configuration files,
  7. and if a file becomes empty, it will be deleted.
  8.  
  9. The contents of the user files may be altered using the Options/Configure IDLE
  10. menu to access the configuration GUI (configDialog.py), or manually.
  11.  
  12. Throughout this module there is an emphasis on returning useable defaults
  13. when a problem occurs in returning a requested configuration value back to
  14. idle. This is to allow IDLE to continue to function in spite of errors in
  15. the retrieval of config information. When a default is returned instead of
  16. a requested config value, a message is printed to stderr to aid in
  17. configuration problem notification and resolution.
  18.  
  19. """
  20. import os
  21. import sys
  22. import string
  23. import macosxSupport
  24. from ConfigParser import ConfigParser, NoOptionError, NoSectionError
  25.  
  26. class InvalidConfigType(Exception): pass
  27. class InvalidConfigSet(Exception): pass
  28. class InvalidFgBg(Exception): pass
  29. class InvalidTheme(Exception): pass
  30.  
  31. class IdleConfParser(ConfigParser):
  32.     """
  33.     A ConfigParser specialised for idle configuration file handling
  34.     """
  35.     def __init__(self, cfgFile, cfgDefaults=None):
  36.         """
  37.         cfgFile - string, fully specified configuration file name
  38.         """
  39.         self.file=cfgFile
  40.         ConfigParser.__init__(self,defaults=cfgDefaults)
  41.  
  42.     def Get(self, section, option, type=None, default=None):
  43.         """
  44.         Get an option value for given section/option or return default.
  45.         If type is specified, return as type.
  46.         """
  47.         if type=='bool':
  48.             getVal=self.getboolean
  49.         elif type=='int':
  50.             getVal=self.getint
  51.         else:
  52.             getVal=self.get
  53.         if self.has_option(section,option):
  54.             #return getVal(section, option, raw, vars, default)
  55.             return getVal(section, option)
  56.         else:
  57.             return default
  58.  
  59.     def GetOptionList(self,section):
  60.         """
  61.         Get an option list for given section
  62.         """
  63.         if self.has_section(section):
  64.             return self.options(section)
  65.         else:  #return a default value
  66.             return []
  67.  
  68.     def Load(self):
  69.         """
  70.         Load the configuration file from disk
  71.         """
  72.         self.read(self.file)
  73.  
  74. class IdleUserConfParser(IdleConfParser):
  75.     """
  76.     IdleConfigParser specialised for user configuration handling.
  77.     """
  78.  
  79.     def AddSection(self,section):
  80.         """
  81.         if section doesn't exist, add it
  82.         """
  83.         if not self.has_section(section):
  84.             self.add_section(section)
  85.  
  86.     def RemoveEmptySections(self):
  87.         """
  88.         remove any sections that have no options
  89.         """
  90.         for section in self.sections():
  91.             if not self.GetOptionList(section):
  92.                 self.remove_section(section)
  93.  
  94.     def IsEmpty(self):
  95.         """
  96.         Remove empty sections and then return 1 if parser has no sections
  97.         left, else return 0.
  98.         """
  99.         self.RemoveEmptySections()
  100.         if self.sections():
  101.             return 0
  102.         else:
  103.             return 1
  104.  
  105.     def RemoveOption(self,section,option):
  106.         """
  107.         If section/option exists, remove it.
  108.         Returns 1 if option was removed, 0 otherwise.
  109.         """
  110.         if self.has_section(section):
  111.             return self.remove_option(section,option)
  112.  
  113.     def SetOption(self,section,option,value):
  114.         """
  115.         Sets option to value, adding section if required.
  116.         Returns 1 if option was added or changed, otherwise 0.
  117.         """
  118.         if self.has_option(section,option):
  119.             if self.get(section,option)==value:
  120.                 return 0
  121.             else:
  122.                 self.set(section,option,value)
  123.                 return 1
  124.         else:
  125.             if not self.has_section(section):
  126.                 self.add_section(section)
  127.             self.set(section,option,value)
  128.             return 1
  129.  
  130.     def RemoveFile(self):
  131.         """
  132.         Removes the user config file from disk if it exists.
  133.         """
  134.         if os.path.exists(self.file):
  135.             os.remove(self.file)
  136.  
  137.     def Save(self):
  138.         """Update user configuration file.
  139.  
  140.         Remove empty sections. If resulting config isn't empty, write the file
  141.         to disk. If config is empty, remove the file from disk if it exists.
  142.  
  143.         """
  144.         if not self.IsEmpty():
  145.             fname = self.file
  146.             try:
  147.                 cfgFile = open(fname, 'w')
  148.             except IOError:
  149.                 os.unlink(fname)
  150.                 cfgFile = open(fname, 'w')
  151.             self.write(cfgFile)
  152.         else:
  153.             self.RemoveFile()
  154.  
  155. class IdleConf:
  156.     """
  157.     holds config parsers for all idle config files:
  158.     default config files
  159.         (idle install dir)/config-main.def
  160.         (idle install dir)/config-extensions.def
  161.         (idle install dir)/config-highlight.def
  162.         (idle install dir)/config-keys.def
  163.     user config  files
  164.         (user home dir)/.idlerc/config-main.cfg
  165.         (user home dir)/.idlerc/config-extensions.cfg
  166.         (user home dir)/.idlerc/config-highlight.cfg
  167.         (user home dir)/.idlerc/config-keys.cfg
  168.     """
  169.     def __init__(self):
  170.         self.defaultCfg={}
  171.         self.userCfg={}
  172.         self.cfg={}
  173.         self.CreateConfigHandlers()
  174.         self.LoadCfgFiles()
  175.         #self.LoadCfg()
  176.  
  177.     def CreateConfigHandlers(self):
  178.         """
  179.         set up a dictionary of config parsers for default and user
  180.         configurations respectively
  181.         """
  182.         #build idle install path
  183.         if __name__ != '__main__': # we were imported
  184.             idleDir=os.path.dirname(__file__)
  185.         else: # we were exec'ed (for testing only)
  186.             idleDir=os.path.abspath(sys.path[0])
  187.         userDir=self.GetUserCfgDir()
  188.         configTypes=('main','extensions','highlight','keys')
  189.         defCfgFiles={}
  190.         usrCfgFiles={}
  191.         for cfgType in configTypes: #build config file names
  192.             defCfgFiles[cfgType]=os.path.join(idleDir,'config-'+cfgType+'.def')
  193.             usrCfgFiles[cfgType]=os.path.join(userDir,'config-'+cfgType+'.cfg')
  194.         for cfgType in configTypes: #create config parsers
  195.             self.defaultCfg[cfgType]=IdleConfParser(defCfgFiles[cfgType])
  196.             self.userCfg[cfgType]=IdleUserConfParser(usrCfgFiles[cfgType])
  197.  
  198.     def GetUserCfgDir(self):
  199.         """
  200.         Creates (if required) and returns a filesystem directory for storing
  201.         user config files.
  202.  
  203.         """
  204.         cfgDir = '.idlerc'
  205.         userDir = os.path.expanduser('~')
  206.         if userDir != '~': # expanduser() found user home dir
  207.             if not os.path.exists(userDir):
  208.                 warn = ('\n Warning: os.path.expanduser("~") points to\n '+
  209.                         userDir+',\n but the path does not exist.\n')
  210.                 try:
  211.                     sys.stderr.write(warn)
  212.                 except IOError:
  213.                     pass
  214.                 userDir = '~'
  215.         if userDir == "~": # still no path to home!
  216.             # traditionally IDLE has defaulted to os.getcwd(), is this adequate?
  217.             userDir = os.getcwd()
  218.         userDir = os.path.join(userDir, cfgDir)
  219.         if not os.path.exists(userDir):
  220.             try:
  221.                 os.mkdir(userDir)
  222.             except (OSError, IOError):
  223.                 warn = ('\n Warning: unable to create user config directory\n'+
  224.                         userDir+'\n Check path and permissions.\n Exiting!\n\n')
  225.                 sys.stderr.write(warn)
  226.                 raise SystemExit
  227.         return userDir
  228.  
  229.     def GetOption(self, configType, section, option, default=None, type=None,
  230.                   warn_on_default=True):
  231.         """
  232.         Get an option value for given config type and given general
  233.         configuration section/option or return a default. If type is specified,
  234.         return as type. Firstly the user configuration is checked, with a
  235.         fallback to the default configuration, and a final 'catch all'
  236.         fallback to a useable passed-in default if the option isn't present in
  237.         either the user or the default configuration.
  238.         configType must be one of ('main','extensions','highlight','keys')
  239.         If a default is returned, and warn_on_default is True, a warning is
  240.         printed to stderr.
  241.  
  242.         """
  243.         if self.userCfg[configType].has_option(section,option):
  244.             return self.userCfg[configType].Get(section, option, type=type)
  245.         elif self.defaultCfg[configType].has_option(section,option):
  246.             return self.defaultCfg[configType].Get(section, option, type=type)
  247.         else: #returning default, print warning
  248.             if warn_on_default:
  249.                 warning = ('\n Warning: configHandler.py - IdleConf.GetOption -\n'
  250.                            ' problem retrieving configration option %r\n'
  251.                            ' from section %r.\n'
  252.                            ' returning default value: %r\n' %
  253.                            (option, section, default))
  254.                 try:
  255.                     sys.stderr.write(warning)
  256.                 except IOError:
  257.                     pass
  258.             return default
  259.  
  260.     def SetOption(self, configType, section, option, value):
  261.         """In user's config file, set section's option to value.
  262.  
  263.         """
  264.         self.userCfg[configType].SetOption(section, option, value)
  265.  
  266.     def GetSectionList(self, configSet, configType):
  267.         """
  268.         Get a list of sections from either the user or default config for
  269.         the given config type.
  270.         configSet must be either 'user' or 'default'
  271.         configType must be one of ('main','extensions','highlight','keys')
  272.         """
  273.         if not (configType in ('main','extensions','highlight','keys')):
  274.             raise InvalidConfigType, 'Invalid configType specified'
  275.         if configSet == 'user':
  276.             cfgParser=self.userCfg[configType]
  277.         elif configSet == 'default':
  278.             cfgParser=self.defaultCfg[configType]
  279.         else:
  280.             raise InvalidConfigSet, 'Invalid configSet specified'
  281.         return cfgParser.sections()
  282.  
  283.     def GetHighlight(self, theme, element, fgBg=None):
  284.         """
  285.         return individual highlighting theme elements.
  286.         fgBg - string ('fg'or'bg') or None, if None return a dictionary
  287.         containing fg and bg colours (appropriate for passing to Tkinter in,
  288.         e.g., a tag_config call), otherwise fg or bg colour only as specified.
  289.         """
  290.         if self.defaultCfg['highlight'].has_section(theme):
  291.             themeDict=self.GetThemeDict('default',theme)
  292.         else:
  293.             themeDict=self.GetThemeDict('user',theme)
  294.         fore=themeDict[element+'-foreground']
  295.         if element=='cursor': #there is no config value for cursor bg
  296.             back=themeDict['normal-background']
  297.         else:
  298.             back=themeDict[element+'-background']
  299.         highlight={"foreground": fore,"background": back}
  300.         if not fgBg: #return dict of both colours
  301.             return highlight
  302.         else: #return specified colour only
  303.             if fgBg == 'fg':
  304.                 return highlight["foreground"]
  305.             if fgBg == 'bg':
  306.                 return highlight["background"]
  307.             else:
  308.                 raise InvalidFgBg, 'Invalid fgBg specified'
  309.  
  310.     def GetThemeDict(self,type,themeName):
  311.         """
  312.         type - string, 'default' or 'user' theme type
  313.         themeName - string, theme name
  314.         Returns a dictionary which holds {option:value} for each element
  315.         in the specified theme. Values are loaded over a set of ultimate last
  316.         fallback defaults to guarantee that all theme elements are present in
  317.         a newly created theme.
  318.         """
  319.         if type == 'user':
  320.             cfgParser=self.userCfg['highlight']
  321.         elif type == 'default':
  322.             cfgParser=self.defaultCfg['highlight']
  323.         else:
  324.             raise InvalidTheme, 'Invalid theme type specified'
  325.         #foreground and background values are provded for each theme element
  326.         #(apart from cursor) even though all these values are not yet used
  327.         #by idle, to allow for their use in the future. Default values are
  328.         #generally black and white.
  329.         theme={ 'normal-foreground':'#000000',
  330.                 'normal-background':'#ffffff',
  331.                 'keyword-foreground':'#000000',
  332.                 'keyword-background':'#ffffff',
  333.                 'builtin-foreground':'#000000',
  334.                 'builtin-background':'#ffffff',
  335.                 'comment-foreground':'#000000',
  336.                 'comment-background':'#ffffff',
  337.                 'string-foreground':'#000000',
  338.                 'string-background':'#ffffff',
  339.                 'definition-foreground':'#000000',
  340.                 'definition-background':'#ffffff',
  341.                 'hilite-foreground':'#000000',
  342.                 'hilite-background':'gray',
  343.                 'break-foreground':'#ffffff',
  344.                 'break-background':'#000000',
  345.                 'hit-foreground':'#ffffff',
  346.                 'hit-background':'#000000',
  347.                 'error-foreground':'#ffffff',
  348.                 'error-background':'#000000',
  349.                 #cursor (only foreground can be set)
  350.                 'cursor-foreground':'#000000',
  351.                 #shell window
  352.                 'stdout-foreground':'#000000',
  353.                 'stdout-background':'#ffffff',
  354.                 'stderr-foreground':'#000000',
  355.                 'stderr-background':'#ffffff',
  356.                 'console-foreground':'#000000',
  357.                 'console-background':'#ffffff' }
  358.         for element in theme.keys():
  359.             if not cfgParser.has_option(themeName,element):
  360.                 #we are going to return a default, print warning
  361.                 warning=('\n Warning: configHandler.py - IdleConf.GetThemeDict'
  362.                            ' -\n problem retrieving theme element %r'
  363.                            '\n from theme %r.\n'
  364.                            ' returning default value: %r\n' %
  365.                            (element, themeName, theme[element]))
  366.                 try:
  367.                     sys.stderr.write(warning)
  368.                 except IOError:
  369.                     pass
  370.             colour=cfgParser.Get(themeName,element,default=theme[element])
  371.             theme[element]=colour
  372.         return theme
  373.  
  374.     def CurrentTheme(self):
  375.         """
  376.         Returns the name of the currently active theme
  377.         """
  378.         return self.GetOption('main','Theme','name',default='')
  379.  
  380.     def CurrentKeys(self):
  381.         """
  382.         Returns the name of the currently active key set
  383.         """
  384.         return self.GetOption('main','Keys','name',default='')
  385.  
  386.     def GetExtensions(self, active_only=True, editor_only=False, shell_only=False):
  387.         """
  388.         Gets a list of all idle extensions declared in the config files.
  389.         active_only - boolean, if true only return active (enabled) extensions
  390.         """
  391.         extns=self.RemoveKeyBindNames(
  392.                 self.GetSectionList('default','extensions'))
  393.         userExtns=self.RemoveKeyBindNames(
  394.                 self.GetSectionList('user','extensions'))
  395.         for extn in userExtns:
  396.             if extn not in extns: #user has added own extension
  397.                 extns.append(extn)
  398.         if active_only:
  399.             activeExtns=[]
  400.             for extn in extns:
  401.                 if self.GetOption('extensions', extn, 'enable', default=True,
  402.                                   type='bool'):
  403.                     #the extension is enabled
  404.                     if editor_only or shell_only:
  405.                         if editor_only:
  406.                             option = "enable_editor"
  407.                         else:
  408.                             option = "enable_shell"
  409.                         if self.GetOption('extensions', extn,option,
  410.                                           default=True, type='bool',
  411.                                           warn_on_default=False):
  412.                             activeExtns.append(extn)
  413.                     else:
  414.                         activeExtns.append(extn)
  415.             return activeExtns
  416.         else:
  417.             return extns
  418.  
  419.     def RemoveKeyBindNames(self,extnNameList):
  420.         #get rid of keybinding section names
  421.         names=extnNameList
  422.         kbNameIndicies=[]
  423.         for name in names:
  424.             if name.endswith(('_bindings', '_cfgBindings')):
  425.                 kbNameIndicies.append(names.index(name))
  426.         kbNameIndicies.sort()
  427.         kbNameIndicies.reverse()
  428.         for index in kbNameIndicies: #delete each keybinding section name
  429.             del(names[index])
  430.         return names
  431.  
  432.     def GetExtnNameForEvent(self,virtualEvent):
  433.         """
  434.         Returns the name of the extension that virtualEvent is bound in, or
  435.         None if not bound in any extension.
  436.         virtualEvent - string, name of the virtual event to test for, without
  437.                        the enclosing '<< >>'
  438.         """
  439.         extName=None
  440.         vEvent='<<'+virtualEvent+'>>'
  441.         for extn in self.GetExtensions(active_only=0):
  442.             for event in self.GetExtensionKeys(extn).keys():
  443.                 if event == vEvent:
  444.                     extName=extn
  445.         return extName
  446.  
  447.     def GetExtensionKeys(self,extensionName):
  448.         """
  449.         returns a dictionary of the configurable keybindings for a particular
  450.         extension,as they exist in the dictionary returned by GetCurrentKeySet;
  451.         that is, where previously used bindings are disabled.
  452.         """
  453.         keysName=extensionName+'_cfgBindings'
  454.         activeKeys=self.GetCurrentKeySet()
  455.         extKeys={}
  456.         if self.defaultCfg['extensions'].has_section(keysName):
  457.             eventNames=self.defaultCfg['extensions'].GetOptionList(keysName)
  458.             for eventName in eventNames:
  459.                 event='<<'+eventName+'>>'
  460.                 binding=activeKeys[event]
  461.                 extKeys[event]=binding
  462.         return extKeys
  463.  
  464.     def __GetRawExtensionKeys(self,extensionName):
  465.         """
  466.         returns a dictionary of the configurable keybindings for a particular
  467.         extension, as defined in the configuration files, or an empty dictionary
  468.         if no bindings are found
  469.         """
  470.         keysName=extensionName+'_cfgBindings'
  471.         extKeys={}
  472.         if self.defaultCfg['extensions'].has_section(keysName):
  473.             eventNames=self.defaultCfg['extensions'].GetOptionList(keysName)
  474.             for eventName in eventNames:
  475.                 binding=self.GetOption('extensions',keysName,
  476.                         eventName,default='').split()
  477.                 event='<<'+eventName+'>>'
  478.                 extKeys[event]=binding
  479.         return extKeys
  480.  
  481.     def GetExtensionBindings(self,extensionName):
  482.         """
  483.         Returns a dictionary of all the event bindings for a particular
  484.         extension. The configurable keybindings are returned as they exist in
  485.         the dictionary returned by GetCurrentKeySet; that is, where re-used
  486.         keybindings are disabled.
  487.         """
  488.         bindsName=extensionName+'_bindings'
  489.         extBinds=self.GetExtensionKeys(extensionName)
  490.         #add the non-configurable bindings
  491.         if self.defaultCfg['extensions'].has_section(bindsName):
  492.             eventNames=self.defaultCfg['extensions'].GetOptionList(bindsName)
  493.             for eventName in eventNames:
  494.                 binding=self.GetOption('extensions',bindsName,
  495.                         eventName,default='').split()
  496.                 event='<<'+eventName+'>>'
  497.                 extBinds[event]=binding
  498.  
  499.         return extBinds
  500.  
  501.     def GetKeyBinding(self, keySetName, eventStr):
  502.         """
  503.         returns the keybinding for a specific event.
  504.         keySetName - string, name of key binding set
  505.         eventStr - string, the virtual event we want the binding for,
  506.                    represented as a string, eg. '<<event>>'
  507.         """
  508.         eventName=eventStr[2:-2] #trim off the angle brackets
  509.         binding=self.GetOption('keys',keySetName,eventName,default='').split()
  510.         return binding
  511.  
  512.     def GetCurrentKeySet(self):
  513.         result = self.GetKeySet(self.CurrentKeys())
  514.  
  515.         if macosxSupport.runningAsOSXApp():
  516.             # We're using AquaTk, replace all keybingings that use the
  517.             # Alt key by ones that use the Option key because the former
  518.             # don't work reliably.
  519.             for k, v in result.items():
  520.                 v2 = [ x.replace('<Alt-', '<Option-') for x in v ]
  521.                 if v != v2:
  522.                     result[k] = v2
  523.  
  524.         return result
  525.  
  526.     def GetKeySet(self,keySetName):
  527.         """
  528.         Returns a dictionary of: all requested core keybindings, plus the
  529.         keybindings for all currently active extensions. If a binding defined
  530.         in an extension is already in use, that binding is disabled.
  531.         """
  532.         keySet=self.GetCoreKeys(keySetName)
  533.         activeExtns=self.GetExtensions(active_only=1)
  534.         for extn in activeExtns:
  535.             extKeys=self.__GetRawExtensionKeys(extn)
  536.             if extKeys: #the extension defines keybindings
  537.                 for event in extKeys.keys():
  538.                     if extKeys[event] in keySet.values():
  539.                         #the binding is already in use
  540.                         extKeys[event]='' #disable this binding
  541.                     keySet[event]=extKeys[event] #add binding
  542.         return keySet
  543.  
  544.     def IsCoreBinding(self,virtualEvent):
  545.         """
  546.         returns true if the virtual event is bound in the core idle keybindings.
  547.         virtualEvent - string, name of the virtual event to test for, without
  548.                        the enclosing '<< >>'
  549.         """
  550.         return ('<<'+virtualEvent+'>>') in self.GetCoreKeys().keys()
  551.  
  552.     def GetCoreKeys(self, keySetName=None):
  553.         """
  554.         returns the requested set of core keybindings, with fallbacks if
  555.         required.
  556.         Keybindings loaded from the config file(s) are loaded _over_ these
  557.         defaults, so if there is a problem getting any core binding there will
  558.         be an 'ultimate last resort fallback' to the CUA-ish bindings
  559.         defined here.
  560.         """
  561.         keyBindings={
  562.             '<<copy>>': ['<Control-c>', '<Control-C>'],
  563.             '<<cut>>': ['<Control-x>', '<Control-X>'],
  564.             '<<paste>>': ['<Control-v>', '<Control-V>'],
  565.             '<<beginning-of-line>>': ['<Control-a>', '<Home>'],
  566.             '<<center-insert>>': ['<Control-l>'],
  567.             '<<close-all-windows>>': ['<Control-q>'],
  568.             '<<close-window>>': ['<Alt-F4>'],
  569.             '<<do-nothing>>': ['<Control-x>'],
  570.             '<<end-of-file>>': ['<Control-d>'],
  571.             '<<python-docs>>': ['<F1>'],
  572.             '<<python-context-help>>': ['<Shift-F1>'],
  573.             '<<history-next>>': ['<Alt-n>'],
  574.             '<<history-previous>>': ['<Alt-p>'],
  575.             '<<interrupt-execution>>': ['<Control-c>'],
  576.             '<<view-restart>>': ['<F6>'],
  577.             '<<restart-shell>>': ['<Control-F6>'],
  578.             '<<open-class-browser>>': ['<Alt-c>'],
  579.             '<<open-module>>': ['<Alt-m>'],
  580.             '<<open-new-window>>': ['<Control-n>'],
  581.             '<<open-window-from-file>>': ['<Control-o>'],
  582.             '<<plain-newline-and-indent>>': ['<Control-j>'],
  583.             '<<print-window>>': ['<Control-p>'],
  584.             '<<redo>>': ['<Control-y>'],
  585.             '<<remove-selection>>': ['<Escape>'],
  586.             '<<save-copy-of-window-as-file>>': ['<Alt-Shift-S>'],
  587.             '<<save-window-as-file>>': ['<Alt-s>'],
  588.             '<<save-window>>': ['<Control-s>'],
  589.             '<<select-all>>': ['<Alt-a>'],
  590.             '<<toggle-auto-coloring>>': ['<Control-slash>'],
  591.             '<<undo>>': ['<Control-z>'],
  592.             '<<find-again>>': ['<Control-g>', '<F3>'],
  593.             '<<find-in-files>>': ['<Alt-F3>'],
  594.             '<<find-selection>>': ['<Control-F3>'],
  595.             '<<find>>': ['<Control-f>'],
  596.             '<<replace>>': ['<Control-h>'],
  597.             '<<goto-line>>': ['<Alt-g>'],
  598.             '<<smart-backspace>>': ['<Key-BackSpace>'],
  599.             '<<newline-and-indent>>': ['<Key-Return> <Key-KP_Enter>'],
  600.             '<<smart-indent>>': ['<Key-Tab>'],
  601.             '<<indent-region>>': ['<Control-Key-bracketright>'],
  602.             '<<dedent-region>>': ['<Control-Key-bracketleft>'],
  603.             '<<comment-region>>': ['<Alt-Key-3>'],
  604.             '<<uncomment-region>>': ['<Alt-Key-4>'],
  605.             '<<tabify-region>>': ['<Alt-Key-5>'],
  606.             '<<untabify-region>>': ['<Alt-Key-6>'],
  607.             '<<toggle-tabs>>': ['<Alt-Key-t>'],
  608.             '<<change-indentwidth>>': ['<Alt-Key-u>'],
  609.             '<<del-word-left>>': ['<Control-Key-BackSpace>'],
  610.             '<<del-word-right>>': ['<Control-Key-Delete>']
  611.             }
  612.         if keySetName:
  613.             for event in keyBindings.keys():
  614.                 binding=self.GetKeyBinding(keySetName,event)
  615.                 if binding:
  616.                     keyBindings[event]=binding
  617.                 else: #we are going to return a default, print warning
  618.                     warning=('\n Warning: configHandler.py - IdleConf.GetCoreKeys'
  619.                                ' -\n problem retrieving key binding for event %r'
  620.                                '\n from key set %r.\n'
  621.                                ' returning default value: %r\n' %
  622.                                (event, keySetName, keyBindings[event]))
  623.                     try:
  624.                         sys.stderr.write(warning)
  625.                     except IOError:
  626.                         pass
  627.         return keyBindings
  628.  
  629.     def GetExtraHelpSourceList(self,configSet):
  630.         """Fetch list of extra help sources from a given configSet.
  631.  
  632.         Valid configSets are 'user' or 'default'.  Return a list of tuples of
  633.         the form (menu_item , path_to_help_file , option), or return the empty
  634.         list.  'option' is the sequence number of the help resource.  'option'
  635.         values determine the position of the menu items on the Help menu,
  636.         therefore the returned list must be sorted by 'option'.
  637.  
  638.         """
  639.         helpSources=[]
  640.         if configSet=='user':
  641.             cfgParser=self.userCfg['main']
  642.         elif configSet=='default':
  643.             cfgParser=self.defaultCfg['main']
  644.         else:
  645.             raise InvalidConfigSet, 'Invalid configSet specified'
  646.         options=cfgParser.GetOptionList('HelpFiles')
  647.         for option in options:
  648.             value=cfgParser.Get('HelpFiles',option,default=';')
  649.             if value.find(';')==-1: #malformed config entry with no ';'
  650.                 menuItem='' #make these empty
  651.                 helpPath='' #so value won't be added to list
  652.             else: #config entry contains ';' as expected
  653.                 value=string.split(value,';')
  654.                 menuItem=value[0].strip()
  655.                 helpPath=value[1].strip()
  656.             if menuItem and helpPath: #neither are empty strings
  657.                 helpSources.append( (menuItem,helpPath,option) )
  658.         helpSources.sort(self.__helpsort)
  659.         return helpSources
  660.  
  661.     def __helpsort(self, h1, h2):
  662.         if int(h1[2]) < int(h2[2]):
  663.             return -1
  664.         elif int(h1[2]) > int(h2[2]):
  665.             return 1
  666.         else:
  667.             return 0
  668.  
  669.     def GetAllExtraHelpSourcesList(self):
  670.         """
  671.         Returns a list of tuples containing the details of all additional help
  672.         sources configured, or an empty list if there are none. Tuples are of
  673.         the format returned by GetExtraHelpSourceList.
  674.         """
  675.         allHelpSources=( self.GetExtraHelpSourceList('default')+
  676.                 self.GetExtraHelpSourceList('user') )
  677.         return allHelpSources
  678.  
  679.     def LoadCfgFiles(self):
  680.         """
  681.         load all configuration files.
  682.         """
  683.         for key in self.defaultCfg.keys():
  684.             self.defaultCfg[key].Load()
  685.             self.userCfg[key].Load() #same keys
  686.  
  687.     def SaveUserCfgFiles(self):
  688.         """
  689.         write all loaded user configuration files back to disk
  690.         """
  691.         for key in self.userCfg.keys():
  692.             self.userCfg[key].Save()
  693.  
  694. idleConf=IdleConf()
  695.  
  696. ### module test
  697. if __name__ == '__main__':
  698.     def dumpCfg(cfg):
  699.         print '\n',cfg,'\n'
  700.         for key in cfg.keys():
  701.             sections=cfg[key].sections()
  702.             print key
  703.             print sections
  704.             for section in sections:
  705.                 options=cfg[key].options(section)
  706.                 print section
  707.                 print options
  708.                 for option in options:
  709.                     print option, '=', cfg[key].Get(section,option)
  710.     dumpCfg(idleConf.defaultCfg)
  711.     dumpCfg(idleConf.userCfg)
  712.     print idleConf.userCfg['main'].Get('Theme','name')
  713.     #print idleConf.userCfg['highlight'].GetDefHighlight('Foo','normal')
  714.